package cd.safe.school.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.androidpn.client.Notifier;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import cd.safe.school.R;
import cd.safe.school.adapter.SchoolSMSAdapter;
import cd.safe.school.bean.FileItem;
import cd.safe.school.bean.Msg;
import cd.safe.school.data.AppData;
import cd.safe.school.util.DateUtil;
import cd.safe.school.util.NetTool;
import cd.safe.school.util.Record;
import cd.safe.school.util.User;

public class SchoolSMS_detail extends Activity implements OnClickListener {
	private static ListView sms_detail;
	private List<Msg> lists = new ArrayList<Msg>();
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			sms_detail.setSelection(lists.size() - 1);
		};
	};
	public static boolean tag = false;
	private SchoolSMSAdapter adapter;
	private Button button_center;
	private Button left_sms;
	private Button right_sms;
	private LinearLayout sms_lay;
	private EditText sms_edit;
	private Button sms_send;
	private String editspeak = "";
	private String imgpath;
	private Button title_butn;
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
	// ----------数据库存储字段
	private String sessionid;
	public static String member;
	private AppData ad = new AppData(this);
	// --------------------
	private Record rd = new Record();
	private SQLiteDatabase db;
	private String[] sendids;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.school_sms_detail);
		// 注册广播
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction("safe_school");
		registerReceiver(mBroadcastReceiver, myIntentFilter);
		sessionid = UUID.randomUUID().toString();
		//
		Notifier.stopactivity = this;
		// 存储数据
		sendids = getIntent().getStringArrayExtra("sendids");

		member = User.userID + sendids;
		db = ad.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("sessionID", sessionid);
		values.put("createTime", DateUtil.getCurrentDate());
		values.put("member", member);
		db.insert("MsgSession", "sessionID", values);
		Cursor c = db.query("MsgContent", null, "sessionID=?",
				new String[] { String.valueOf(sessionid) }, null, null, null);
		if (c != null) {
			if (c.moveToNext()) {
				Msg ms = new Msg();
				int msgID = c.getInt(c.getColumnIndex("msgID"));
				int sessionID = c.getInt(c.getColumnIndex("sessionID"));
				String createTime = c.getString(c.getColumnIndex("createTime"));
				String msgContent = c.getString(c.getColumnIndex("msgContent"));

				ms.setCreatetime(createTime);
				ms.setMsgid(msgID);
				ms.setSessionid(sessionID);
				ms.setMsgcontent(msgContent);
				lists.add(ms);

			}
		}

		//
		title_butn = (Button) findViewById(R.id.title_butn);
		title_butn.setVisibility(View.INVISIBLE);
		sms_detail = (ListView) findViewById(R.id.sms_detail);
		button_center = (Button) findViewById(R.id.center_sms);
		left_sms = (Button) findViewById(R.id.left_sms);
		right_sms = (Button) findViewById(R.id.right_sms);
		sms_lay = (LinearLayout) findViewById(R.id.sms_lay);
		sms_edit = (EditText) findViewById(R.id.sms_edit);
		sms_send = (Button) findViewById(R.id.sms_send);
		left_sms.setOnClickListener(this);
		sms_send.setOnClickListener(this);
		right_sms.setOnClickListener(this);

		button_center.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					rd.start(Environment.getExternalStorageDirectory()
							+ "/safeschool_record/test.mp3");
					// 按住执行
					Toast.makeText(SchoolSMS_detail.this, "请说话",
							Toast.LENGTH_SHORT).show();
					break;
				case MotionEvent.ACTION_UP:
					// 松开执行
					rd.stop();
					final Map<String, Object> params = new HashMap<String, Object>();
					params.put("filename", "test.mp3");
					params.put("msg", "1");
					params.put("infoType", "1");
					params.put("receiveId", sendids);
					params.put("filetype", "1");

					final List<FileItem> items = new ArrayList<FileItem>();
					FileItem fi = new FileItem();
					fi.setFieldName("file");
					fi.setPath(Environment.getExternalStorageDirectory()
							+ "/safeschool_record/test.mp3");
					items.add(fi);
					new Thread(new Runnable() {

						@Override
						public void run() {
							String ret = NetTool
									.postFileFormParams(
											"http://125.64.132.84:8080/jxt/app/res/upload",
											params, items);

						}
					}).start();

					// Toast.makeText(SchoolSMS_detail.this, "说话结束",
					// Toast.LENGTH_SHORT).show();
					break;
				case MotionEvent.ACTION_MOVE:
					// 移动执行

					break;
				}
				return false;
			}
		});
		
		// 如果s不为空，表示从列表打开
		String s = getIntent().getStringExtra("tag");
		// if (s == null) {
		// if (!tag) {
		// ChatTuisong tuisong = new ChatTuisong();
		// tuisong.setApiKey(getIntent().getStringExtra(
		// Constants.NOTIFICATION_API_KEY));
		// tuisong.setFrom(getIntent().getStringExtra(
		// Constants.NOTIFICATION_FROM));
		// tuisong.setMessage(getIntent().getStringExtra(
		// Constants.NOTIFICATION_MESSAGE));
		// tuisong.setNotificationId(getIntent().getStringExtra(
		// Constants.NOTIFICATION_ID));
		// tuisong.setPacketId(getIntent().getStringExtra(
		// Constants.PACKET_ID));
		// tuisong.setTitle(getIntent().getStringExtra(
		// Constants.NOTIFICATION_TITLE));
		// tuisong.setUri(getIntent().getStringExtra(
		// Constants.NOTIFICATION_URI));
		// tuisong.setFlag(false);
		//
		// lists.add(tuisong);
		// }
		// }
		tag = true;
		adapter = new SchoolSMSAdapter(SchoolSMS_detail.this, lists, handler);
		sms_detail.setSelection(lists.size() - 1);
		sms_detail.setAdapter(adapter);

		sms_detail.setDivider(null);
		if ((getIntent().getStringExtra("message")) != null
				&& !"".equals((getIntent().getStringExtra("message")))) {
			Msg m = new Msg();
			m.setCreatetime(DateUtil.getCurrentDate());
			m.setMsgid(20);
			m.setMsgcontent(getIntent().getStringExtra("message"));
			loaddata(m);

		}

	}

	public void loaddata(Msg msg) {

		lists.add(msg);
		adapter.notifyDataSetChanged();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// lists.clear();
		tag = false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
			Uri selectedImage = data.getData();

			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,

			filePathColumn, null, null, null);

			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

			imgpath = cursor.getString(columnIndex);
			final Map<String, Object> params = new HashMap<String, Object>();
			params.put("filename",
					imgpath.substring(imgpath.lastIndexOf("/") + 1));
			params.put("msg", "1");
			params.put("infoType", 0);
			params.put("receiveId", sendids);
			params.put("filetype", 1);

			final List<FileItem> items = new ArrayList<FileItem>();
			FileItem fi = new FileItem();
			fi.setFieldName("file");
			fi.setPath(imgpath);
			items.add(fi);
			new Thread(new Runnable() {
				@Override
				public void run() {
					String ret = NetTool.postFileFormParams(
							"http://125.64.132.84:8080/jxt/app/res/upload",
							params, items);

				}
			}).start();

			cursor.close();

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.sms_send:
			sms_lay.setVisibility(View.GONE);
			final Map<String, Object> params = new HashMap<String, Object>();
			params.put("receiveId", sendids);
			params.put("infoType", "0");
			params.put("dialogId", UUID.randomUUID());
			params.put("msg", sms_edit.getText().toString());
			params.put("filename", "");
			params.put("canReply", "1");

			final List<FileItem> items = new ArrayList<FileItem>();

			new Thread(new Runnable() {

				@Override
				public void run() {
					String ret = NetTool.postFileFormParams(
							"http://125.64.132.84:8080/jxt/app/file/upload",
							params, items);

				}
			}).start();

			Msg m = new Msg();
			m.setMsgcontent(sms_edit.getText().toString());
			m.setFlag(true);
			m.setCreatetime(DateUtil.getCurrentDate());
			m.setMsgid(1);
			loaddata(m);
			adapter.notifyDataSetChanged();

			break;
		case R.id.left_sms:
			if (sms_lay.getVisibility() == View.GONE) {
				sms_edit.setText(null);
				sms_lay.setVisibility(View.VISIBLE);

			} else {
				sms_lay.setVisibility(View.GONE);

			}

			break;

		case R.id.right_sms:
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, 1001);

			break;

		}

	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("safe_school")) {
				Msg ms = new Msg();
				ms.setMsgcontent(intent.getStringExtra("message"));
				ms.setCreatetime(DateUtil.getCurrentDate());
				ms.setMsgid(10);

				// chatTuisong.setApiKey(intent.getStringExtra("apiKey"));
				// chatTuisong.setFrom(intent.getStringExtra("from"));
				// chatTuisong.setMessage(intent.getStringExtra("message"));
				// chatTuisong.setNotificationId(intent
				// .getStringExtra("notificationId"));
				// chatTuisong.setPacketId(intent.getStringExtra("packetId"));
				// chatTuisong.setTitle(intent.getStringExtra("title"));
				// chatTuisong.setUri(intent.getStringExtra("uri"));
				// chatTuisong.setFlag(false);
				loaddata(ms);

			}
		}

	};

}
